package com.campus.delivery.service;

import com.campus.delivery.handler.NativeWebSocketHandler;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * WebSocket消息控制器
 * 基于原生WebSocket协议的消息处理
 */
@Service
@Slf4j
public class WebSocketService {
    
    @Autowired
    private NativeWebSocketHandler nativeWebSocketHandler;



    /**
     * 向指定配送员发送出餐通知
     * 基于原生WebSocket协议
     * 
     * @param deliveryId 配送员ID
     * @param mealMessage 出餐消息内容
     */
    public void sendMealReadyNotification(Integer deliveryId, String mealMessage) {
        log.info("向配送员{}发送出餐通知: {}", deliveryId, mealMessage);
        nativeWebSocketHandler.sendMealReadyNotification(deliveryId, mealMessage);
    }

    /**
     * 广播系统通知给所有在线配送员
     * 基于原生WebSocket协议
     * 
     * @param message 系统通知消息
     */
    public void broadcastSystemNotification(String message) {
        log.info("广播系统通知: {}", message);
        nativeWebSocketHandler.broadcastSystemNotification(message);
    }
    
    /**
     * 广播订单状态变更给所有在线配送员
     * 基于原生WebSocket协议
     * 
     * @param orderId 订单ID
     * @param newDeliveryProcess 新的配送状态
     * @param grabbedByDeliveryId 抢单的配送员ID
     */
    public void broadcastOrderStatusChange(String orderId, Integer newDeliveryProcess, Integer grabbedByDeliveryId) {
        log.info("广播订单状态变更: 订单{}, 新状态{}, 抢单配送员{}", orderId, newDeliveryProcess, grabbedByDeliveryId);
        nativeWebSocketHandler.broadcastOrderStatusChange(orderId, newDeliveryProcess, grabbedByDeliveryId);
    }
    
    /**
     * 获取WebSocket连接统计信息
     * 
     * @return 连接统计信息
     */
    public String getConnectionStats() {
        int onlineDeliveries = nativeWebSocketHandler.getOnlineDeliveryCount();
        int totalConnections = nativeWebSocketHandler.getTotalConnectionCount();
        return String.format("在线配送员数: %d, 总连接数: %d", onlineDeliveries, totalConnections);
    }
}